package com.zjut.an.html.manager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.annotation.Resource;

import com.zjut.an.config.manager.AnConfigManager;
import com.zjut.an.news.dao.AnNews;
import com.zjut.an.news.manager.AnNewsManager;
import com.zjut.an.util.system.Config;
import com.zjut.an.webclass.dao.AnWebclass;
import com.zjut.an.webclass.manager.AnWebclassManager;


public class HtmlManager {
	@Resource(name = "AnConfigManager")
	AnConfigManager cmanager;
	
	@Resource(name = "AnNewsManager")
	AnNewsManager nmanager;
	
	HttpServletRequest request;
	HttpServletResponse response;
	
	public HtmlManager() {
	}
	
	public void setHttp(HttpServletRequest req, HttpServletResponse res) {
		try {
			this.request = req;
			this.response = res;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean CreatINDEX() {
		
		System.out.println("@"+cmanager.getSingleConfigInfoByName("网站域名"));
		System.out.println(request.getSession().getServletContext().getRealPath("/")+"html/menu.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/menu.jsp", request.getSession().getServletContext().getRealPath("/")+"html/menu.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/MobileFrame.jsp", request.getSession().getServletContext().getRealPath("/")+"html/MobileFrame.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/banner.jsp", request.getSession().getServletContext().getRealPath("/")+"html/banner.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/bottom.jsp", request.getSession().getServletContext().getRealPath("/")+"html/bottom.jsp");
		//this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/index_m.jsp", cmanager.getSingleConfigInfoByName("网站目录")+"/html"+"/index_m.html");
		return this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/index.jsp", cmanager.getSingleConfigInfoByName("网站目录")+"/html"+"/index.html");
	}
	
	public boolean CreatNews(AnNews news) {
		String url = cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/news.jsp?neId="+news.getNeId();// 模板文件地址
		String uploadPath = cmanager.getSingleConfigInfoByName("网站目录")+"/html";
		String savepath = uploadPath+"/n"+news.getNeId()+".html";// 生成文件地址
		return this.JspToHtmlByURL(url, savepath);
	}
	
	public boolean CreatWebclass(AnWebclass webclass) {
		//System.out.println("#################### creat:"+webclass.getWcName());
		String url = cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/newsclass.jsp?wcId="+webclass.getWcId();// 模板文件地址
		String uploadPath = cmanager.getSingleConfigInfoByName("网站目录")+"/html";
		//System.out.println("#################### creat:"+uploadPath);
		String savepath = uploadPath+"/w"+webclass.getWcId()+"_1.html";// 生成文件地址
		int totalpage = nmanager.getPubDatasByTopWcId(1, Config.getShowitemnumber(), null, null, webclass).getTotalpage();
		if (totalpage==0)totalpage=1;
		for (int i=1; i<=totalpage; i++) {
			url = cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/newsclass.jsp?wcId="+webclass.getWcId()+"&showItemNumber="+Config.getShowitemnumber()+"&pageNumber="+i;// 模板文件地址
			uploadPath = request.getSession().getServletContext().getRealPath("/")+"html";
			savepath = uploadPath+"/w"+webclass.getWcId()+"_"+i+".html";// 生成文件地址
			this.JspToHtmlByURL(url, savepath);
		}
		
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/menu.jsp", request.getSession().getServletContext().getRealPath("/")+"html/menu.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/MobileFrame.jsp", request.getSession().getServletContext().getRealPath("/")+"html/MobileFrame.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/right.jsp", request.getSession().getServletContext().getRealPath("/")+"html/right.jsp");
		this.JspToHtmlByURL(cmanager.getSingleConfigInfoByName("网站域名")+"/jsp/bottom.jsp", request.getSession().getServletContext().getRealPath("/")+"html/bottom.jsp");
		//this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/reg.jsp",request.getSession().getServletContext().getRealPath("/")+"html/reg.jsp");
		//this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/login.jsp",request.getSession().getServletContext().getRealPath("/")+"html/login.jsp");
		//this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/user.jsp",request.getSession().getServletContext().getRealPath("/")+"html/user.jsp");
		//this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/getpassword1.jsp",request.getSession().getServletContext().getRealPath("/")+"html/getpassword1.jsp");
		//this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/getpassword2.jsp",request.getSession().getServletContext().getRealPath("/")+"html/getpassword2.jsp");
		this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/newssearch.jsp",request.getSession().getServletContext().getRealPath("/")+"html/newssearch.jsp");
		//this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/logout.jsp",request.getSession().getServletContext().getRealPath("/")+"html/logout.jsp");
		this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/message.jsp",request.getSession().getServletContext().getRealPath("/")+"html/message.jsp");
		this.copyFile(request.getSession().getServletContext().getRealPath("/")+"jsp/IPConfirm.jsp",request.getSession().getServletContext().getRealPath("/")+"html/IPConfirm.jsp");
		return true;
	}
	
	public boolean JspToHtmlByURL(String u, String path) {
		// 从utl中读取html存为str

		String str = "";
		try {
			URL url = new URL(u);
			URLConnection uc = url.openConnection();
			
			uc.setReadTimeout(30000);  
			InputStream is = uc.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String line=null;
			while ((line=br.readLine())!=null) {
				str += line + "\n";
			}
			Pattern p=Pattern.compile("news\\.jsp\\?neId=\\d+");
			Matcher m=p.matcher(str);
			while(m.find()) {
				String v = m.group().replace("?", "[?]");
				String v2 = m.group().replace("news.jsp?neId=", "../html/n")+".html";
			    str = str.replaceFirst(v, v2);
			}
			p=Pattern.compile("newsclass\\.jsp\\?wcId=\\d+&showItemNumber=\\d+&pageNumber=\\d+");
			m=p.matcher(str);
			while(m.find()) {
				
				String v = m.group().replace("?", "[?]");
				String v2 = m.group().replace("newsclass.jsp?wcId=", "../html/w").replace("&showItemNumber=10&pageNumber=", "_")+".html";
				//System.out.println("####################"+v+":"+v2);
			    str = str.replaceFirst(v, v2);
			}
			p=Pattern.compile("newsclass\\.jsp\\?wcId=\\d+");
			m=p.matcher(str);
			System.out.println(str);
			while(m.find()) {
				String v = m.group().replace("?", "[?]");
				String v2 = m.group().replace("newsclass.jsp?wcId=", "../html/w")+"_1.html";
				//System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@"+m+"           "+v+"            "+v2);
			    str = str.replaceFirst(v, v2);
			    //System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@"+str);
			}
			str = str.replaceAll("index.jsp", "index.html");
			if (str.contains("</html>")) {
				is.close();
				// 写入文件
				BufferedWriter o=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
				
				if (path.contains(".jsp"))str="<%@ page language=\"java\" import=\"java.util.*\" contentType=\"text/html;charset=UTF-8\" pageEncoding=\"UTF-8\"%>"+str;
				o.write(str);
				o.close();
				str = "";
				return true;
			} else {
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean copyFile(String from, String to) {  
		String str = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(from), "UTF-8"));  
			
			String line=null;
			while ((line=br.readLine())!=null) {
				str += line + "\n";
			}
			Pattern p=Pattern.compile("news\\.jsp\\?neId=\\d+");
			Matcher m=p.matcher(str);
			while(m.find()) {
				String v = m.group().replace("?", "[?]");
				String v2 = m.group().replace("news.jsp?neId=", "../html/n")+".html";
			    str = str.replaceFirst(v, v2);
			}
			p=Pattern.compile("newsclass\\.jsp\\?wcId=\\d+&showItemNumber=\\d+&pageNumber=\\d+");
			m=p.matcher(str);
			while(m.find()) {
				
				String v = m.group().replace("?", "[?]");
				String v2 = m.group().replace("newsclass.jsp?wcId=", "../html/w").replace("&showItemNumber=10&pageNumber=", "_")+".html";
				//System.out.println("####################"+v+":"+v2);
			    str = str.replaceFirst(v, v2);
			}
			p=Pattern.compile("newsclass\\.jsp\\?wcId=\\d+");
			m=p.matcher(str);
			while(m.find()) {
				String v = m.group().replace("?", "[?]");
				String v2 = m.group().replace("newsclass.jsp?wcId=", "../html/w")+"_1.html";
			    str = str.replaceFirst(v, v2);
			}
			str = str.replaceAll("index.jsp", "index.html");
			if (str.contains("</html>")) {
				// 写入文件
				BufferedWriter o=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to),"UTF-8"));
				o.write(str);
				o.close();
				str = "";
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
